using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Permissions;
using System.Security;

namespace Log4MyNet
{
    internal class Writer:IDisposable, Log4MyNet.IWriter
    {
        string _filePath = string.Empty;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="fileFullPath"></param>
        /// 
        internal Writer(string fileFullPath)
        {
            
            _filePath = fileFullPath;
            if (Properties.Settings.Default.IsAlwaysCreateNewFile)
            {
                if (File.Exists(fileFullPath))
                {
                    File.Delete(fileFullPath);
                }
            }

            if (!File.Exists(fileFullPath))
            {
                FileStream fs=File.Create(_filePath);
                fs.Flush();
                fs.Close();
                fs.Dispose();
            }
            

            if (Properties.Settings.Default.IsAppendMarkString)
            {
                string mark = "\r\n|*****************************************|\r\n";
                WriteLog(String.Format("\r\nLog time {0} made by xlag {1}\r\n", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),mark));
            }
        }

        public void WriteLineLog(string msg)
        {
            WriteLog(msg, true);
        }

        public void WriteLog(string msg)
        {
            WriteLog(msg, false);
        }


        private void WriteLog(string msg,bool isNeedNewLine)
        {
            //fStream = File.Open(_filePath, FileMode.OpenOrCreate);

            //int curPos = fStream.ReadByte();
            //byte[] bytes = new UTF8Encoding(true).GetBytes(msg);
            //fStream.Write(bytes, 0, bytes.Length);
            //fStream.Flush();
            //fStream.Close();
            //FileIOPermission perm = new FileIOPermission(FileIOPermissionAccess.AllAccess, _filePath);
            //try
            //{
            //    perm.Demand();
            //}
            //catch(SecurityException es)
            //{
            //    throw es;
            //}

            using (StreamWriter w = File.AppendText(_filePath))
            {
                if (isNeedNewLine)
                {
                    w.WriteLine(msg);
                }
                else
                {
                    w.Write(msg);
                }

                w.Flush();
                w.Close();
            }
        }

        #region IDisposable Members

        public void Dispose()
        {

        }

        #endregion
    }
}
